package com.slipper.sfts.websocket;

import com.slipper.PaasContext;
import com.slipper.common.util.GsonUtil;
import com.slipper.common.util.StockUtil;
import com.slipper.common.util.StringUtil;
import com.slipper.sfts.redis.RedisSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.*;
import java.util.stream.Collectors;

public class WebsocketHandler extends TextWebSocketHandler {
    private static final Logger logger = LoggerFactory.getLogger(WebsocketHandler.class);

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) {
        logger.info("获取客户端消息：" + message.getPayload());
        MessageVO vo = GsonUtil.fromJson(message.getPayload(), MessageVO.class);

        if ("tick".equals(vo.getType())) {
            String stockCode = StockUtil.getStockCode(vo.getCode());
            if (StringUtil.isBlank(stockCode)) {
                return;
            }

            Map<String, Object> data = new HashMap<>();
            data.put("flag", session.getAttributes().get("memberId"));
            data.put("code", stockCode);
            PaasContext.getBean(RedisSender.class).sendMsg("get_tick", GsonUtil.toJson(data));
        } else if ("tick_list".equals(vo.getType())) {
            String codeList = Arrays.stream(vo.getCode().split(","))
                    .filter(StringUtil::isNotBlank)
                    .map(StockUtil::getStockCode)
                    .collect(Collectors.joining(","));

            if (StringUtil.isBlank(codeList)) {
                return;
            }

            Map<String, Object> data = new HashMap<>();
            data.put("flag", session.getAttributes().get("memberId"));
            data.put("code", codeList);
            PaasContext.getBean(RedisSender.class).sendMsg("get_tick_list", GsonUtil.toJson(data));
        }
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) {
        String memberId = session.getAttributes().get("memberId").toString();
        WebsocketManager.addSession(memberId, session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        WebsocketManager.closeSession(session);
    }
}
